package cs4383;

import javax.media.j3d.BoundingBox;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.vecmath.Point3d;
import javax.vecmath.Vector3d;

import org.apache.log4j.Logger;

import ar.PropManager;

public class ModelHelper {

	public static Logger logger = Logger.getLogger(ModelHelper.class);
	
	public static TransformGroup loadModel(String modelFnm, double scale,
			boolean hasCoords)
	// load the model, rotating and scaling it
	{
		logger.debug("loadModel");
		PropManager propMan = new PropManager(modelFnm, hasCoords);

		// get the TG for the prop (model)
		TransformGroup propTG = propMan.getTG();

		// rotate and scale the prop
		Transform3D modelT3d = new Transform3D();
		modelT3d.rotX(Math.PI / 2.0);
		// the prop lies flat on the marker; rotate forwards 90 degrees so it is
		// standing
		Vector3d scaleVec = calcScaleFactor(propTG, scale); // scale the prop
		modelT3d.setScale(scaleVec);

		TransformGroup modelTG = new TransformGroup(modelT3d);
		modelTG.addChild(propTG);
		
		TransformGroup tg = new TransformGroup();
		tg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
		tg.addChild(modelTG);
		return tg;
//		return modelTG;
	} // end of loadModel()

	public static Vector3d calcScaleFactor(TransformGroup modelTG, double scale)
	// Scale the prop based on its original bounding box size
	{
		BoundingBox boundbox = new BoundingBox(modelTG.getBounds());
		System.out.println(boundbox);

		// obtain the upper and lower coordinates of the box
		Point3d lower = new Point3d();
		boundbox.getLower(lower);
		Point3d upper = new Point3d();
		boundbox.getUpper(upper);

		// store the largest X, Y, or Z dimension and calculate a scale factor
		double max = 0.0;
		if (Math.abs(upper.x - lower.x) > max)
			max = Math.abs(upper.x - lower.x);

		if (Math.abs(upper.y - lower.y) > max)
			max = Math.abs(upper.y - lower.y);

		if (Math.abs(upper.z - lower.z) > max)
			max = Math.abs(upper.z - lower.z);

		double scaleFactor = scale / max;
		System.out.printf("max dimension: %.3f;  scale factor: %.3f\n", max,
				scaleFactor);

		// limit the scaling so that a big model isn't scaled too much
		if (scaleFactor < 0.0005)
			scaleFactor = 0.0005;

		return new Vector3d(scaleFactor, scaleFactor, scaleFactor);
	} // end of calcScaleFactor()

}
